@file:JvmName("DataUtil")

package com.lindroy.androidplayer.utils

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lindroy.androidplayer.logic.model.LoginModel
import com.tencent.mmkv.MMKV

/**
 * @author Lin
 * @date 2022/2/16
 * @function
 */

private const val KEY_LOGIN_INFO = "login_info"
private const val KEY_IS_LOGIN = "is_login"
private const val KEY_IS_SHOW_BANNER = "is_show_banner"
private const val KEY_IS_SHOW_TOP_ARTICLE = "is_show_article"
private const val KEY_SEARCH_HISTORY = "search_history"


private val kvAppData = MMKV.mmkvWithID("app_data")

fun saveLoginInfo(loginInfo: LoginModel) {
    kvAppData.encode(KEY_LOGIN_INFO, Gson().toJson(loginInfo))
    saveLogin(true)
}

var kvIsShowBanner: Boolean = false
    get() = kvAppData.decodeBool(KEY_IS_SHOW_BANNER, true)
    set(value) {
        field = value
        kvAppData.encode(KEY_IS_SHOW_BANNER, value)
    }

var kvIsShowTopArticle: Boolean = false
    get() = kvAppData.decodeBool(KEY_IS_SHOW_TOP_ARTICLE, true)
    set(value) {
        field = value
        kvAppData.encode(KEY_IS_SHOW_TOP_ARTICLE, value)
    }

val kvLoginInfo: LoginModel?
    get() = kvAppData.decodeString(KEY_LOGIN_INFO).let {
        if (it != null && it.isNotEmpty()) {
            Gson().fromJson(kvAppData.decodeString(KEY_LOGIN_INFO), LoginModel::class.java)
        } else {
            null
        }
    }

var kvSearchHistory: List<String>
    get() = kvAppData.decodeString(KEY_SEARCH_HISTORY)?.let {
        Gson().fromJson(it, object : TypeToken<List<String>>() {}.type)
    } ?: listOf()
    set(value) {
        kvAppData.encode(
            KEY_SEARCH_HISTORY, Gson().toJson(
                if (value.size >= 10) {
                    value.subList(0, 9)
                } else value
            )
        )
    }


fun saveLogin(isLogin: Boolean) {
    kvAppData.encode(KEY_IS_LOGIN, isLogin)
}

val isLogin: Boolean
    get() = kvAppData.decodeBool(KEY_IS_LOGIN)

fun clearUserInfo() {
    kvAppData.clearAll()
}